package com.xgp.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();

        for(int i = 1;i <= 10;i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "",temp + "");
            },String.valueOf(i)).start();
        }

        for(int i = 1;i <= 10;i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            },String.valueOf(i)).start();
        }

    }
}

class MyCacheLock {
    private volatile Map<String,Object> map = new HashMap<>();
    //读写锁
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    // 存，写的过程
    public void put(String key,Object value) {
        try {
            lock.writeLock().lock();
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写入OK");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }


    }

    // 取，读
    public Object get(String key) {
        try {
            lock.readLock().lock();
            System.out.println(Thread.currentThread().getName() + "读取" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取OK");

            return o;
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
        return null;
    }
}
/**
 * 自定义缓存
 */
class MyCache {
    private volatile Map<String,Object> map = new HashMap<>();

    // 存，写的过程
    public void put(String key,Object value) {
        System.out.println(Thread.currentThread().getName() + "写入" + key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName() + "写入OK");
    }

    // 取，读
    public Object get(String key) {
        System.out.println(Thread.currentThread().getName() + "读取" + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取OK");

        return o;
    }
}
